import { redirect, LoaderFunction } from "react-router-dom";

// 检查用户是否已登录
export function checkAuthToken() {
  const token = localStorage.getItem("token");
  return !!token;
}

// 创建需要鉴权的 loader 函数
export function useAuth(loader?: LoaderFunction): LoaderFunction {
  return function (...args: any[]): ReturnType<LoaderFunction> {
    if (!checkAuthToken()) {
      const params = new URLSearchParams();
      const [{ request }] = args;
      params.set("redirectTo", new URL(request.url).pathname);
      return redirect(`/login?${params.toString()}`);
    }

    // 如果有 token，继续执行原始 loader
    if (loader) {
      return loader(...(args as Parameters<typeof loader>));
    }

    // 如果没有原始 loader，只返回鉴权成功
    return { isAuthenticated: true };
  };
}
